#ifndef _R_H_
#define _R_H_

#include "Preferences.h"
#include "vector"

#define RECV_PIN 0
#define SEND_PIN 3

Preferences storage;
static bool isRecording = false;
std::vector<int> durationList;

void startRecord()
{
    isRecording = true;
    durationList.clear();
}

void stopRecord()
{
    if (!isRecording)
    {
        return;
    }
    isRecording = false;
}

void playbackRecord()
{
    pinMode(SEND_PIN, OUTPUT);

    Serial.println("Playback record start.");

    digitalWrite(SEND_PIN, LOW);
    delayMicroseconds(2000);

    for (int i = 0; i < durationList.size(); i++)
    {
        int duration = durationList[i];

        digitalWrite(SEND_PIN, duration > 0 ? HIGH : LOW);
        delayMicroseconds(abs(duration));
    }

    digitalWrite(SEND_PIN, LOW);
    Serial.println("Playback record done.");
}

void onReceiveChange()
{
    static unsigned long lastTime = 0;

    const long time = micros();

    int duration = time - lastTime;
    int status = digitalRead(RECV_PIN);

    // 间隔时间小于1s
    if (duration < 1e6)
    {
        if (status == HIGH)
        {
            duration = -duration;
        }

        if (isRecording)
        {
            durationList.push_back(duration);
        }
    }

    lastTime = time;
}

void setupRecord()
{
    int status = digitalRead(RECV_PIN);
    Serial.printf("Read pin %d: %d\n", RECV_PIN, status);

    attachInterrupt(digitalPinToInterrupt(RECV_PIN), onReceiveChange, CHANGE);
}

#endif